package queue;
//基于数组实现队列（循环队列）
public class MyQueueByArray {
    private String[] data;  //储存元素的数组
    private int first = 0;   //队头
    private int last = 0;   //队尾
    private int size = 0;   //队列长度
    //无参构造，默认容量20
    public MyQueueByArray(){
        this(20);
    }
    //有参构造
    public MyQueueByArray(int capacity) {
        this.data = new String[capacity];
    }
    //扩容
    private void resize(){
        //1.5倍进行扩容得到新的数组
        String[] newData = new String[data.length + (data.length >> 1)];
        int i = 0;
        int index = first;
        //将原数组的数组拷贝到新数组
        while(index != last){
            newData[i++] = data[index++];
            if(index == data.length){
                index = 0;
            }
        }
        newData[i++] = data[index++];
        first = 0;  //注意更新队首和队尾
        last = i;
        data = newData;
    }
    //入队
    public void offer(String elem){
        //扩容
        if(size == data.length){
            resize();
        }
        data[last++] = elem;
        //队尾等于数组长度时，重置队尾为0
        if(last == data.length){
            last = 0;
        }
        size++;
    }
    //出队
    public String poll(){
        if(size == 0){
            return null;
        }
        //记录出队元素
        String ret = data[first];

//        first++;
//        if (first == data.length){
//            first = 0;
//        }
        //队首等于数组长度时，重置队首为0
        first = (first + 1) % data.length;

        size++;

        return ret;
    }
    //获取队首元素
    public String peek(){
        if(size == 0){
            return null;
        }

        return data[first];
    }
    //判空
    public boolean isEmpty(){
        return size == 0;
    }
    //获取队列大小
    public int size(){
        return size;
    }

    public static void main(String[] args) {
        MyQueueByArray queue = new MyQueueByArray(10);
        System.out.println(queue.size());
        System.out.println(queue.isEmpty());
        queue.offer("wang");
        queue.offer("shuang");
        queue.offer("xi");
        queue.offer("gege");
        queue.offer("小钰");

        System.out.println(queue.size());
        System.out.println(queue.isEmpty());
        System.out.println(queue.peek());
        System.out.println(queue.poll());
        System.out.println(queue.peek());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());
        System.out.println(queue.poll());

        System.out.println(queue.peek());
    }
}
